<template>
    <div style="position: relative;">
        <el-page-header @back="goBack" content="查看销售单">
            <div slot="content" style="display: flex;align-items: center;">
                <div>查看销售单</div>
                <div style="margin-left: 12px;" v-if="!pageType">
                    <div v-if="formData.is_pay" style="border: 1px solid #0099ff;color: #0099ff;font-size: 12px;padding: 0 5px;border-radius: 2px;">已结清</div>
                    <div v-else style="border: 1px solid #f55;color: #f55;font-size: 12px;padding: 0 5px;border-radius: 2px;">未结清</div>
                </div>
                <div v-if="showPostStatus&&!pageType" style="margin-left: 12px;">
                    <div v-if="formData.delivery_status" style="border: 1px solid #0099ff;color: #0099ff;font-size: 12px;padding: 0 5px;border-radius: 2px;">已发货</div>
                    <div v-else style="border: 1px solid #f55;color: #f55;font-size: 12px;padding: 0 5px;border-radius: 2px;">未发货</div>
                </div>
            </div>
        </el-page-header>
        <!-- <div class="common_line"></div> -->
        <el-form ref="formData" :model="formData" label-width="auto" style="margin-top: 20px;">
            <el-collapse v-model="activeNames">
                <el-collapse-item title="基本信息" name="base">
                    <el-row>
                        <el-col :span="6">
                            <el-form-item label="客户名称:">
                                <div>{{ formData.customName }}</div>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="开单日期:">
                                <div>{{ formData.sale_date }}</div>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="订单编号:">
                                <div>{{ formData.corp_order_no }}</div>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6" v-if="setForm.sale">
                            <el-form-item label="销售人员:">
                                <div class="set_user_done">{{ formData.sale.map(item => item.username).join('、') }}</div>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6" v-if="setForm.builder">
                            <el-form-item label="施工人员:">
                                <div class="set_user_done">{{ formData.builder.map(item => item.username).join('、') }}</div>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6" v-if="setForm.rebates">
                            <el-form-item label="红包(元):">
                                <div>{{ '￥'+formData.rebates }}</div>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6" v-if="setForm.delivery_address">
                            <el-form-item label="联系地址:">
                                <div>{{ formData.delivery_address }}</div>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="经办人:">
                                <div>{{ formData.handler_name }}</div>
                            </el-form-item>
                        </el-col>
                        <template v-if="customFields&&customFields.length">
                            <el-col :span="6" v-for="(item, index) in customFields" :key="'field_'+item.modelName">
                                <el-form-item :label="item.labelName+':'" v-if="setForm['set'+(index+1)]">
                                    <div>{{ formData[item.modelName] }}</div>
                                </el-form-item>
                            </el-col>
                        </template>
                    </el-row>
                </el-collapse-item>
                <!-- <el-collapse-item title="销售商品" name="product"> -->
                <div style="font-size: 14px;font-weight: bold;height: 48px;line-height: 48px;">销售商品</div>
                <el-row>
                    <el-table :data="formData.goods" border max-height="360" class="prod_table">
                        <el-table-column label="序号" width="80" align="center" prop="index" />
                        <el-table-column label="商品名称" align="center" prop="name" />
                        <el-table-column label="商品编号" align="center" prop="goods_no" />
                        <el-table-column label="条形码" align="center" prop="barcode" />
                        <el-table-column label="数量" align="center" prop="num" />
                        <el-table-column label="单价" align="center" prop="unit_price" />
                        <el-table-column label="总额" align="center">
                            <template slot-scope="scope">
                                <div v-if="scope.row.num&&scope.row.unit_price">
                                    {{ (parseFloat(scope.row.num)*parseFloat(scope.row.unit_price)).toFixed(2) }}</div>
                            </template>
                        </el-table-column>
                        <el-table-column label="单位" align="center" width="100" prop="unitName" />
                        <el-table-column label="批次" align="center" width="100" prop="batchName" />
                        <el-table-column label="生产日期" align="center" width="100" prop="productDate" />
                        <el-table-column label="规格" align="center" prop="specifications" />
                        <el-table-column label="库存剩余" align="center" prop="current_inventory_quantity" />
                        <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip />
                    </el-table>
                </el-row>
                <!-- </el-collapse-item> -->
                 
                <div style="font-size: 14px;font-weight: bold;height: 48px;line-height: 48px;">价格明细</div>
                <!-- <el-collapse-item title="价格明细" name="price" > -->
                <el-row style="display: flex; flex-wrap: wrap;">
                    <el-col :span="8">
                        <el-form-item label="商品总价:">
                            <div>{{ '￥'+formData.goods_sum_price }}</div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="总数量:">
                            <div>{{ formData.goods_count }}</div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="订单金额:">
                            <div style="color: red;">{{ '￥'+formData.order_price }}</div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8" v-if="setForm.payment_discount">
                        <el-form-item label="结款优惠:">
                            <div>{{ '￥'+formData.payment_discount }}</div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="待收款:">
                            <div>{{ '￥'+formData.unPayMoney }}</div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="结算账户:">
                            <div>{{ paymentStr }}</div>
                        </el-form-item>
                    </el-col>
                </el-row>

                <div style="font-size: 14px;font-weight: bold;height: 48px;line-height: 48px;">其他信息</div>
                <el-row>
                    <el-col :span="24">
                        <el-checkbox style="margin: 0 0 20px 30px;" v-model="formData.is_need_invoice">需要发票</el-checkbox>
                    </el-col>
                    <el-col :span="24" v-if="formData.is_need_invoice">
                        <div class="invoice_view">
                            <div v-for="(item, index) in formData.invoice_list" :key="'invo_'+index" class="cell">
                                <i class="el-icon-tickets" style="font-size: 17px;color: #949482;"></i>
                                <div style="margin-left: 8px;">
                                    <div class="info">
                                        <span>{{ '发票号：'+item.invoice_no }}</span>
                                        <span v-if="item.remark">{{ '，备注：'+item.remark }}</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </el-col>
                    <el-col :span="24">
                        <el-checkbox @change="addressChange" style="margin: 0 0 20px 30px;"
                             v-model="formData.is_need_postsend">配送信息</el-checkbox>
                    </el-col>
                    <el-col :span="24" v-if="formData.is_need_postsend">
                        <div class="send_view">
                            <div class="title">
                                <span>配送方式</span>
                                <el-radio-group v-model="formData.delivery_method">
                                    <el-radio :label="1">商家配送</el-radio>
                                    <el-radio :label="2">客户自提</el-radio>
                                    <el-radio :label="3">快递物流</el-radio>
                                </el-radio-group>
                            </div>
                            <div class="contents">
                                <div class="address" v-if="formData.delivery_method===1">
                                    <div class="base">
                                        <div class="info">{{ '收货人：'+formData.extend_data.receiver_name }}</div>
                                        <div class="info">{{ '收货人电话：'+formData.extend_data.receiver_phone }}</div>
                                    </div>
                                    <div class="addr">{{ '收货地址：'+formData.cityName+' '+formData.extend_data.detail }}</div>
                                </div>
                                <div class="fastmail" v-else-if="formData.delivery_method===3">
                                    <div class="item">{{ '快递公司：'+formData.extend_data.express_corp_name }}</div>
                                    <div class="item" style="margin-top: 10px;">{{ '快递单号：'+formData.extend_data.express_no }}</div>
                                </div>
                            </div>
                        </div>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="备注:">
                            <div>{{ formData.remark }}</div>
                        </el-form-item>
                    </el-col>
                </el-row>

                <div v-if="fileLists&&fileLists.length">
                    <div style="font-size: 14px;font-weight: bold;height: 48px;line-height: 48px;">附件</div>
                    <div class="file_list">
                        <div v-for="item in fileLists" :key="'file_'+item.id" class="file" @click="downloadFile(item)">
                            {{ item.file_name }}
                        </div>
                    </div>
                </div>
                <!-- </el-collapse-item> -->
            </el-collapse>
        </el-form>

        <!-- 收款记录弹窗 -->
        <el-dialog title="收款记录" :visible.sync="showRecordAlert" :close-on-click-modal="false" width="30%" center append-to-body>
            <div style="padding-left: 40px">
                <el-timeline :reverse="false">
                    <el-timeline-item
                        v-for="(activity, index) in records"
                        :key="'rec_'+index"
                        :timestamp="activity.timestamp">
                        <div style="display: flex;align-items: center;justify-content: space-between;padding-right: 100px;">
                            <span>{{ activity.content }}</span>
                            <span>{{ activity.pay_type_str }}</span>
                        </div>
                    </el-timeline-item>
                </el-timeline>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="showRecordAlert=false">关 闭</el-button>
            </span>
        </el-dialog>

        <!-- 付尾款弹窗 -->
        <el-dialog title="收款" :visible.sync="showPaymentPop" :close-on-click-modal="false" width="30%" center append-to-body>
            <div>
                <el-form :model="paymentForm" label-width="auto" ref="paymentForm" :rules="rules">
                    <el-form-item label="待收金额:">
                        <div>{{ '￥'+formData.unPayMoney }}
                            <span>{{ '(剩余待收 ￥'+lastReceive+')'}}</span>
                        </div>
                    </el-form-item>
                    <el-form-item label="本次收款:" prop="orders_fee">
                        <el-input style="width: 280px;" maxlength="100" v-model="paymentForm.orders_fee" placeholder="请输入" clearable />
                    </el-form-item>
                    <el-form-item label="结算账户:">
                        <el-select style="width: 280px;" v-model="paymentForm.pay_type" placeholder="请选择">
                            <el-option v-for="item in payTypes" :key="'pay_'+item.value" 
                                :label="item.label" :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="备注:">
                        <el-input maxlength="200" show-word-limit type="textarea" :autosize="{ minRows: 2, maxRows: 6 }"
                         v-model="paymentForm.remark" placeholder="请输入" style="width: 280px;" clearable />
                    </el-form-item>
                </el-form>  
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="showPaymentPop=false">关 闭</el-button>
                <el-button class="btn_primary_color" @click="createReceiveOrder">确 定</el-button>
            </span>
        </el-dialog>

        <div class="bottom">
            <div class="btns" v-if="!pageType">
                <el-button class="btn" v-if="showPostStatus && !formData.delivery_status" @click="sendGoods">发 货</el-button>
                <el-button class="btn btn_primary_color" v-if="!formData.is_pay" @click="showReceivedMoney">收尾款</el-button>
                <template v-if="formData.payment_record&&formData.payment_record.length">
                    <!-- <div style="color: #ccc;">|</div> -->
                    <div class="record" @click="showRecord">收款记录</div>
                </template>
            </div>
            <div class="btns" v-else>
                <el-button v-if="pageType=='1'||pageType=='3'" class="btn btn_primary_color" @click="dealOrder('pass')">通过</el-button>
                <el-button v-if="pageType=='1'" class="btn btn_remove_color" @click="dealOrder('unpass')">驳回</el-button>
            </div>
        </div>
    </div>
</template>

<script>
import { getOrderSet, getOrderNo, addOrder, updateOrder, infoOrder, getProductDate, postDelivery } from '@/api/order';
import { getCustomerList, infoCustomer, addReceivePayment } from "@/api/cooperate";
import { getUserList } from "@/api/user";
import { listProduct, getPriceLevel, getTreeList } from '@/api/product';
import { getPriceRemember } from '@/api/common'
import { cityCodes } from "@/utils/city";
import { todoApply } from '@/api/login'
const moment = require('moment')

export default {
    name: 'queryOrder',
    data() {
        return {
            showLoading: false,
            showDialog: false,
            showChooseProduct: false,
            showRecordAlert: false,
            isEdit: false,
            isDraft: false,
            isAdmin: false,
            showMore: false,
            showAddInvoice: false,
            corp: '',
            pageTitle: '',
            orderId: '',
            setForm: {},
            customFields: [],
            activeNames: ['base'],
            showPostStatus: false,
            formData: {
                customer: '',
                corp: '',
                goods: [],
                goods_count: '0',
                order_price: 0,
                payment_discount: '',
                rebates: '',
                delivery_address: '',
                current_paid_payment: 0,
                sale_date: '',
                sale: [],
                builder: [],
                is_pay: 1,
                handler_user: '',
                handler_name: '',
                pending_payment: '',
                goods_sum_price: '0.00',
                is_draft: false,  //是否草稿
                pay_type: 2,
                is_need_invoice: false,
                invoice_list: [],
                is_need_postsend: false,
                delivery_method: 1,
                extend_data: {
                    receiver_name: "",
                    receiver_phone: "",
                    province_code: "",
                    city_code: "",
                    area_code: "",
                    province_name: "",
                    city_name: "",
                    area_name: "",
                    detail: "",
                    express_no: "",
                    express_corp_name: "",
                    selectCity: []
                },
                cityName: '',
                pay_type_name: '',
                remark: ''
            },
            searchGoods: [],
            customerList: [],
            dialogTitle: '',
            chooseUsers: [],
            salesList: [],
            userLists: [],
            chooseGoods: [],
            middleGoods: [],
            goodsList: [],
            pageParam: {
                page: 1,
                num: 10
            },
            total: 0,
            userType: '',
            loadOver: false,  //是否加载完
            queryParams: {
                status: '',
                brand__icontains: '',
                type__icontains: '',
                specifications__icontains: '',
                category_one_level: '',
                category: '',
                search: ''
            },
            categorys: [],
            selectCates: [],
            exchangeId: null,  //预售转单id
            buttonList: [
                { name: '保存草稿', type: 'commit', id:'1' },
                { name: '结算', type: 'commit', id:'2' },
                { name: '取消', type: 'cancel', id:'3' }
            ],
            records: [],
            payTypes: [
                {label: '微信', value: 2},
				{label: '支付宝', value: 5},
				{label: '现金', value: 1},
				{label: '银行转账', value: 3},
				{label: '其他', value: 4}
            ],
            tableKey: Date.now(),
            showChooseNumberPop: false,
            chooseNumberInfo: {},
            popShowType: '',  //录入商品数量弹窗弹出类型:1 从表单列表  2 从选择商品弹窗
            batchLists: [],
            priceLevels: [],
            current_customer_price_level: '',  //当前选择客户的价格等级字段
            scanCode: '',
            invoiceDialogTitle: '新增开票',
            invoiceForm: {
                index: 0,
                invoice_no: '',
                remark: ''
            },
            invoiceRules:{
                invoice_no: [
                    { required: true, message: "请输入发票号", trigger: 'blur' },
                ]
            },
            showPaymentPop: false,
            paymentForm: {
                corp: '',
                customer: '',
                handler_user: '',
                orders_date: '',
                orders_fee: '',
                pay_type: 2,
                record_type: 1, //1收款--销售开单|2付款--销售退单
                remark: '',
                file_id_list: [],
                order_relations: []
            },
            rules:{
                orders_fee: [
                    { required: true, message: "请输入本次收款金额", trigger: 'blur' },
                ]
            },
            cityOptions: cityCodes,
            fileLists: [],
            pageType: '',
            todoId: '',
            hashTable: new Map() // 哈希表存储编码到路径的映射
        }
    },
    props: {
        corpId: {
            type: Number
        },
        editId: {
            type: Number
        }
    },
    computed: {
        // 计算剩余待收
        lastReceive() {
            let res = parseFloat(this.formData.unPayMoney)
            if (this.paymentForm.orders_fee){
                res = this.$common.subtractFloat(parseFloat(this.formData.unPayMoney), parseFloat(this.paymentForm.orders_fee))
            }
            return res.toFixed(2)
        },
        paymentStr() {
            let str = '未支付'
            if (this.formData.payment_record && this.formData.payment_record.length){
                let names = this.formData.payment_record.map(item => item.pay_type_str)
                str = names.join('、')
            }
            return str
        }
    },
    watch: {
        '$route.query.bussId8': {
            immediate: true, // 首次加载时触发
            handler(newId) {
                if (newId) {
                    this.corp = this.$store.state.corpId
                    this.orderId = newId
                    this.pageType = this.$route.query.type || ''
                    this.todoId = this.$route.query.todoId || ''
                    this.initPageData()
                }
            }
        }
    },
    mounted() {
        this.corp = this.corpId
        if (this.editId){
            this.orderId = this.editId
            this.initPageData()
        }
    },
    methods: {
        goBack() {
            this.$emit('hidden')
        },
        // 处理待办
        dealOrder(type) {
            todoApply({
                todo_id: this.todoId,
                status: type=='pass'?'已通过':'驳回',
                corp_id: this.formData.corp
            }).then(res => {
                this.$message.success('处理成功')
                this.$emit('hidden', {isRefresh: 'true'})
            })
        },
        initPageData() {
            this.isAdmin = this.$store.state.isAdmin
            this.formData.handler_name = this.$store.state.userInfo.username
            this.formData.handler_user = this.$store.state.userInfo.id

            this.getOrderFiledSet()
            this.getPriceRememberSettings()
            this.getOrderInfo()
        },
        sendGoods() {
            postDelivery({
                corp_id: this.corp,
                order_id_list: [this.orderId]
            }).then(res => {
                if (res.code == 200){
                    this.$message.success('发货成功')
                    this.getOrderInfo()
                }
            })
        },
        addressChange(val) {
            this.$set(this.formData, 'is_need_postsend', val)
            this.$forceUpdate()
        },
        buildHashTable() {
            const traverse = (node, parentPath = []) => {
                const currentPath = [...parentPath, node.name];
                this.hashTable.set(node.code, {
                    name: node.name,
                    path: currentPath.join('&')
                });

                if (node.children) {
                    node.children.forEach(child => traverse(child, currentPath));
                }
            };

            this.cityOptions.forEach(root => traverse(root));
        },
        getScanCode(e) {
            if (e.key=='Enter' && e.target.id=='scanCodeGun'){
                console.log('扫描结果 --- '+e.target.value)
                this.searchProducts(e.target.value, 'scan')
                this.scanCode = ''
            }
        },
        setInputFocus(e) {
            if (e.target.id != 'scanCodeGun'){
                document.getElementById('scanCodeGun').focus()
            }
        },
        checkWhichIsActive(e) {
            const inputElement = document.getElementById('scanCodeGun');
            if (document.activeElement.tagName=='BODY' && document.activeElement!=inputElement){
                document.getElementById('scanCodeGun').focus()
            }
        },
        // 获取自定义字段
        getOrderFiledSet() {
            getOrderSet({corp: this.corp}).then(res => {
                let list = res.data.data.set_order_list
                if (list.length){
                    this.setForm = list[0]

                    let set_field_name = list[0].set_field_name
                    if (!set_field_name){
                        return
                    }
                    for (var i = 1; i < 11; i++) {
                        let keyName = set_field_name['name'+i]
                        if (keyName) {
                            this.$set(this.formData, 'custom_field'+i, '')
                            this.customFields.push({
                                labelName: keyName,
                                modelName: 'custom_field'+i
                            })
                        }
                    }
                }else{
                    this.setId = null
                }
            })
        },
        downloadFile(item) {
            location.href = item.url_show
        },
        // 获取详情
        getOrderInfo() {
            let _this = this
            infoOrder(this.orderId,  {corp: this.corp}).then(res => {
                let infos = res.data.data
                infos.pay_type = 2
                _this.formData = infos
                _this.formData.customName = infos.customer_detail.customer_name
                _this.formData.is_pay = infos.is_pay==true?1:0
                _this.formData.remark = infos.remark?infos.remark:''
                if (infos.paid_payment){
                    _this.formData.unPayMoney = _this.$common.subtractFloat(parseFloat(infos.order_price), parseFloat(infos.paid_payment))
                }else{
                    _this.formData.unPayMoney = 0
                }
                
                _this.formData.handler_name = infos.handler_user_detail ? infos.handler_user_detail.username : ''
                
                if (infos.draft_payment){
                    _this.$set(_this.formData, 'current_paid_payment', parseFloat(infos.draft_payment))
                    // _this.formData.current_paid_payment = parseFloat(infos.draft_payment)
                }

                _this.formData.builder = []
                _this.formData.sale = []
                _this.formData.goods = []
                if (infos.is_need_invoice && infos.sale_invoice_show){
                    _this.formData.invoice_list = infos.sale_invoice_show.filter((el, ind) => {
                        el.index = ind
                        return el
                    })
                }else {
                    _this.formData.invoice_list = []
                }

                // 配送信息
                if (infos.delivery_method > 0){
                    _this.formData.is_need_postsend = true
                    _this.formData.extend_data = infos.sale_extend_show
                    if (infos.delivery_method === 1){
                        if (infos.sale_extend_show.province_name){
                            _this.formData.cityName = infos.sale_extend_show.province_name+'/'+ 
                                infos.sale_extend_show.city_name+'/'+infos.sale_extend_show.area_name
                        }else{
                            _this.formData.cityName = ''
                        }
                    }
                }else{
                    _this.formData.is_need_postsend = false
                }

                // 附件
                _this.fileLists = infos.file_list_show || []

                if (infos.builder_commissions && infos.builder_commissions.length){  //施工人员
                    infos.builder_commissions.forEach((item, index) => {
                        _this.formData.builder.push({
                            index: index+1,
                            name: item.builder_commission.builder_name,
                            builder: item.builder_commission.builder_id,
                            type:"施工",
                            commission: item.builder_commission.commission
                        })
                    })
                }
                if (infos.sale_commissions && infos.sale_commissions.length){  //销售人员
                    infos.sale_commissions.forEach((item, index) => {
                        _this.formData.sale.push({
                            index: index+1,
                            name: item.sale_commission.sale_name,
                            sale: item.sale_commission.sale_id,
                            type:"销售",
                            commission: item.sale_commission.commission
                        })
                    })
                }
                let all_price = 0
                let all_count = 0
                if (infos.batch_date_record_detail && infos.batch_date_record_detail.length){  //商品

                    infos.batch_date_record_detail.forEach((item, index) => {
                        let allUnits = []
                        item.main_unit_name = item.goods_details.unit_show?item.goods_details.unit_show.name:item.goods_details.unit
                        item.main_unit_id = item.goods_details.unit_show?item.goods_details.unit_show.id:''
                        item.is_multi_unit = false
                        item.unitName = item.main_unit_name
                        item.selectUnitId = item.main_unit_id
                        item.unit_price = item.goods_details.unit_price
                        item.num = item.goods_details.num
                        if (item.deputy_unit) {  //多单位
                            item.unitName = item.deputy_unit_detail?item.deputy_unit_detail.unit_name:''
                            item.is_multi_unit = true
                            item.selectUnitId = item.deputy_unit_detail.goods_unit 
                            item.unit_price = parseFloat(item.deputy_price)
                            item.num = _this.$common.multiplyDivision(parseFloat(item.num), parseFloat(item.deputy_ratio)).toFixed(2)
                            let formatterName = '1'+item.unitName+'='+parseFloat(item.deputy_ratio)+item.goods_details.unit_show.name
                            item.deputy_unit_detail.formatterName = formatterName
                            item.deputy_unit_detail.unit_price = item.unit_price
                            let mainArray = [{
                                goods_unit: item.goods_details.unit_show.id,
                                unit_name: item.goods_details.unit_show.name,
                                formatterName: item.goods_details.unit_show.name,
                                unit_price: item.goods_details.unit_price,
                                unit_retail_price: item.goods_details.unit_retail_price || 0,
                                unit_purchase_price: item.goods_details.unit_purchase_price || 0
                            }]
                            let array = mainArray.concat([item.deputy_unit_detail])
                            allUnits = array.filter(_item => {
                                _item.selected = _item.unit_name==item.unitName
                                return _item
                            })
                        }
                        _this.formData.goods.push({
                            index: index+1,
                            name: item.goods_details.name,
                            id: item.goods_details.id,
                            goods_id: item.goods_details.id,
                            num: parseFloat(item.num),
                            select_num: parseFloat(item.num),
                            unit: item.goods_details.unit,
                            unit_price: item.unit_price,
                            goods_no: item.goods_details.goods_no || '',
                            imageUrl: (item.goods_details.image?item.goods_details.image.url:'https://anhuiyaoying.com/icon/default.png'),
                            current_inventory_quantity: parseFloat(item.goods_details.current_inventory_quantity),
                            unitArray: allUnits,
                            select_unit_id: item.selectUnitId,
                            unitName: item.unitName,
                            main_unit_name: item.main_unit_name,
                            is_multi_unit: item.is_multi_unit,
                            batchName: item.batch_date_account_detail.batch_name || '',
                            productDate: item.batch_date_account_detail.produce_date || ''
                        })
                        all_count += parseFloat(item.goods_details.num)
                        all_price += (_this.$common.multiplyFloat(item.goods_details.num, item.goods_details.unit_price))
                    })
                }
                
                if (infos.goods_sum_price) {
                    _this.formData.goods_sum_price = parseFloat(infos.goods_sum_price)
                }else{
                    _this.formData.goods_sum_price = all_price
                }
                
                if (infos.goods_count) {
                    _this.formData.goods_count = parseFloat(infos.goods_count)
                }else{
                    _this.formData.goods_count = all_count
                }
                _this.formData.payment_discount = parseFloat(infos.payment_discount)
                _this.formData.order_price = parseFloat(infos.order_price)
                // _this.handleStyle()
            })
        },
        addCell() {
            this.formData.goods.push({
                index: this.formData.goods.length+1,
                name: '',
                goods_no: '',
                barcode: '',
                num: '',
                unit_price: '',
                unitName: '',
                specifications: '',
                current_inventory_quantity: '',
                remark: ''
            })
        },
        handleStyle() {
            if (this.formData.goods.length) {
                this.formData.goods.forEach(item => {
                    if (item.id) {
                        document.getElementsByClassName('prod_search')[item.index-1].classList.remove('show_product_cell')
                    }
                })
            }
        },
        handleRemove(row) {
            document.getElementsByClassName('prod_search')[row.index-1].classList.add('show_product_cell')
            function removeByIndexAndReindex(arr, indexToRemove) {
                // 使用 filter 方法过滤掉指定 index 的元素
                let newArray = arr.filter(item => item.index!== indexToRemove);
                return newArray;
            }
            let res = removeByIndexAndReindex(this.formData.goods, row.index)
            if (res.length){
                this.formData.goods = res.filter((item, index) => {
                    item.index = index+1
                    return item
                })
            }else{
                this.formData.goods = [{
                    index: 1,
                    name: '',
                    goods_no: '',
                    barcode: '',
                    num: '',
                    unit_price: '',
                    unitName: '',
                    specifications: '',
                    current_inventory_quantity: '',
                    remark: ''
                }]
            }
            this.middleGoods = this.formData.goods
            this.recalculate()
            let that = this
            this.$nextTick(() => {
                that.formData.goods.forEach(item => {
                    let index = item.index-1
                    if (item.id){
                        document.getElementsByClassName('prod_search')[index].classList.remove('show_product_cell')
                    }else{
                        if (!document.getElementsByClassName('prod_search')[index].classList.contains('show_product_cell')){
                            document.getElementsByClassName('prod_search')[index].classList.add('show_product_cell')
                        }
                    }
                })
            })
        },
        // 生成订单编号
        createOrderNo() {
            getOrderNo({corp: this.corp}).then(res => {
                this.formData.corp_order_no = res.data.data.order_no
                this.$forceUpdate()
            })
        },
        // 设置施工、销售人员
        setUsers(type) {
            if (type == 'sale'){
                this.dialogTitle = '设置销售人员'
                if (this.formData.sale.length) {
                    this.chooseUsers = this.formData.sale
                }else{
                    this.chooseUsers = [{
                        index: 1,
                        username: '',
                        sale: '',
                        id: '',
                        type: "销售",
                        commission: '0'
                    }]
                }
            }else if (type == 'build'){
                this.dialogTitle = '设置施工人员'
                if (this.formData.builder.length) {
                    this.chooseUsers = this.formData.builder
                }else{
                    this.chooseUsers = [{
                        index: 1,
                        username: '',
                        id: '',
                        builder: '',
                        type: "施工",
                        commission: '0'
                    }]
                }
            }
            this.showDialog = true
        },
        chooseDone() {
            if (this.chooseUsers.length){
                let type = this.chooseUsers[0].type
                if (type == '销售'){
                    this.formData.sale = this.chooseUsers
                }else{
                    this.formData.builder = this.chooseUsers
                }
            }
            this.showDialog = false
        },
        closeDialog() {
            this.chooseUsers = []
            this.chooseGoods = []
            this.showChooseProduct = false
            this.showDialog = false
        },
        addUser(item) {
            if (item.type == '销售'){
                this.chooseUsers.push({
                    index: this.chooseUsers.length+1,
                    username: '',
                    sale: '',
                    id: '',
                    type:"销售",
                    commission: '0'
                })
            }else{
                this.chooseUsers.push({
                    index: this.chooseUsers.length+1,
                    name: '',
                    builder: '',
                    id: '',
                    type:"施工",
                    commission: '0'
                })
            }
        },
        removeUser(item) {
            let users = this.chooseUsers.filter(_item => {
				return _item.index != item.index
			})
            this.chooseUsers = users.filter((_item, _index) => {
                _item.index = _index + 1
                return _item
            })
            this.$forceUpdate()
        },

        // 选择商品
        showChooseGoods() {
            // if (this.formData.goods.length){
            //     this.chooseGoods = this.formData.goods.filter(item => {
            //         if (item.id){
            //             item.select_num = item.num
            //             return item
            //         }
            //     })
            //     this.middleGoods = this.chooseGoods
            // }else{
            //     this.chooseGoods = []
            // }
            this.middleGoods = []
            this.chooseGoods = []
            this.handleQuery()
            // this.handleSelectRow()
            this.showChooseProduct = true
        },
        chooseGoodsOk() {
            // 库存校验
            let flag = false, msg = '';
            for (let i = 0; i < this.chooseGoods.length; i++) {
                const item = this.chooseGoods[i];
                if (!item.select_num) {
                    flag = true;
                    msg = '请输入【' + item.name + '】的数量';
                    break; 
                } else if (parseFloat(item.select_num) > item.current_inventory_quantity) {
                    flag = true;
                    msg = '【' + item.name + '】库存不足，请修改数量';
                    break; 
                } else if (item.is_multi_unit) {  //多单位
                    const findItem = item.unitArray.find(_item => _item.goods_unit==item.goods_unit)
                    let all_num = 0
                    if (findItem && findItem.deputy_ratio) {
                        all_num = this.$common.multiplyFloat(parseFloat(item.select_num), parseFloat(findItem.deputy_ratio))
                    }
                    if (all_num > item.current_inventory_quantity){
                        flag = true;
                        msg = '【' + item.name + '】库存不足，请修改数量';
                        break; 
                    }
                }
            }
            if (flag) {
                this.$message.error(msg)
                return
            }
            this.mergeArrays()
            this.formData.goods.forEach(item => {
                item.num = item.select_num
            })
            this.recalculate()
            // if (!this.activeNames.includes('price')){
            //     this.activeNames.push('price')
            // }
            this.showChooseProduct = false
            this.chooseGoods = []
            this.middleGoods = this.formData.goods
        },
        mergeArrays() {
            let array1 = this.formData.goods
            let array2 = this.chooseGoods
            // 1. 找到 array1 中所有空项的索引（id 为空的位置）
            const emptyIndices = array1
            .map((item, index) => (!item.id ? index : -1))
            .filter(index => index !== -1);

            // 2. 按顺序填充 array1 的空位（跳过已有数据的项）
            let filledCount = 0;
            for (let i = 0; i < array2.length; i++) {
                if (filledCount < emptyIndices.length) {
                    // 填充空位，动态生成 index
                    const targetIndex = emptyIndices[filledCount];
                    this.$set(array1, targetIndex, {
                    ...array2[i],
                    index: targetIndex + 1, // 根据 array1 的位置生成 index
                    });
                    filledCount++;
                } else {
                    // 超出空位数量时，追加到末尾，index 自动递增
                    array1.push({
                    ...array2[i],
                    index: array1.length + 1, // 确保 index 连续
                    });
                }
            }
            this.tableKey = Date.now();
            let that = this
            this.$nextTick(() => {
                that.formData.goods.forEach((item, index) => {
                    if (item.id) {
                        document.getElementsByClassName('prod_search')[index].classList.remove('show_product_cell')
                    }
                })
            })
        },
        mergeArrays1() {
            let array1 = this.formData.goods
            let array2 = this.chooseGoods
            if (array2.length > array1.length){
                // 遍历 array2
                for (let i = 0; i < array2.length; i++) {
                    const item = array2[i];
                    
                    // 相同部分
                    if (i < array1.length) {
                        array2[i].index = i+1
                        array1[i] = array2[i]
                    }else{
                        const newIndex = array1.length + 1;
                        array1.push({ ...item, index: newIndex });
                    }
                }
            }else{
                // 遍历 array1
                for (let i = 0; i < array1.length; i++) {
                    // 相同部分
                    if (i < array2.length) {
                        array2[i].index = i+1
                        array1[i] = array2[i]
                    }else{
                        Object.assign({}, array1[i], {
                            name: '',
                            goods_no: '',
                            barcode: '',
                            num: '',
                            unit_price: '',
                            unitName: '',
                            specifications: '',
                            current_inventory_quantity: ''
                        })
                    }
                }
            }
            this.tableKey = Date.now();
            let that = this
            this.$nextTick(() => {
                that.formData.goods.forEach((item, index) => {
                    if (item.id) {
                        document.getElementsByClassName('prod_search')[index].classList.remove('show_product_cell')
                    }
                })
            })
        },
        getCustomers(){
            getCustomerList({
                corp: this.corp,
                category: '',
                page: 1,
                num: 999
            }).then(res => {
                let headerItem = {
                    name: '姓名',
                    cateName: '分类',
                    phone: '电话号码',
                    address: '地址',
                    disabled: true
                }
                let cur_level = ''
                this.customerList = res.data.data.customer_list.filter((item, index) => {
                    if (index === 0 && !this.orderId){
                        this.formData.customer = item.id
                        this.formData.delivery_address = item.address
                        cur_level = item.price_level
                    }
                    item.disabled = false
                    if (item.category_detail && item.category_detail.name) {
                        item.cateName = item.category_detail.name
                    }else{
                        item.cateName = ''
                    }
                    return item
                })
                this.customerList.unshift(headerItem)
                this.getUnitLevels(cur_level)
            })
        },
        getUsers() {
            getUserList({
                corp: this.corp,
                page: 1,
                num: 999
            }).then(res => {
                let headerItem = {
                    username: '姓名',
                    phone_no: '手机号',
                    statusName: '状态',
                    email: '邮箱',
                    disabled: true
                }
                this.userLists = res.data.users.filter(item => {
                    item.statusName = item.is_on_job ? '在职' : '离职'
                    item.disabled = false
                    return item
                })
                this.userLists.unshift(headerItem)
            })
        },
        customerChange(val) {
            if (val === 'customerList'){
                this.$router.push({
                    path: 'customerList',
                    query: {
                        from: 'order'
                    }
                })
                return
            }
            this.customerList.forEach(item => {
                if (item.id === val) {
                    this.formData.delivery_address = item.address
                    if (item.price_level){
                        let findItem = this.priceLevels.find(_item => _item.id===item.price_level)
                        this.current_customer_price_level = findItem.price_column_name
                    }
                    // 获取收货地址
                    this.getCustomerAddress(item.id)
                    // 更新价格等级
                    this.updatePriceLevel()
                }
            })
        },
        // 获取收货地址
        getCustomerAddress(id) {
            infoCustomer(id, {corp: this.corp}).then(res => {
                let info = res.data.data
                if (info.address_data_show && info.address_data_show.length){
                    let defaultItem = info.address_data_show.find(item => item.is_default)
                    this.formData.extend_data.receiver_name = defaultItem.receiver_name
                    this.formData.extend_data.receiver_phone = defaultItem.receiver_phone
                    this.formData.extend_data.province_code = defaultItem.province_code
                    this.formData.extend_data.city_code = defaultItem.city_code
                    this.formData.extend_data.area_code = defaultItem.area_code
                    this.formData.extend_data.province_name = defaultItem.province_name
                    this.formData.extend_data.city_name = defaultItem.city_name
                    this.formData.extend_data.area_name = defaultItem.area_name
                    this.formData.extend_data.detail = defaultItem.detail
                    this.formData.extend_data.selectCity = [defaultItem.province_code, defaultItem.city_code, defaultItem.area_code]
                }else{
                    this.formData.extend_data = {
                        receiver_name: "",
                        receiver_phone: "",
                        province_code: "",
                        city_code: "",
                        area_code: "",
                        province_name: "",
                        city_name: "",
                        area_name: "",
                        detail: "",
                        express_no: "",
                        express_corp_name: "",
                        selectCity: []
                    }
                }
            })
        },
        // 更新价格等级
        updatePriceLevel() {
            let that = this
            this.formData.goods.forEach(item => {
                if (item.unitArray && item.unitArray.length) {
                    item.unitArray.forEach(_item => {
                        if (_item.selected && that.current_customer_price_level) {
                            item.unit_price = _item[that.current_customer_price_level] || '0.00'
                        }
                    })
                }
            })
        },
        userChoose(val) {
            let selectItem = this.userLists.find(_item => _item.id===val)
            if (selectItem){
                this.chooseUsers.forEach(_item => {
                    if (selectItem.id === _item.id){
                        _item.username = selectItem.username
                        if (_item.type == 'sale'){
                            _item.sale = val
                        }else{
                            _item.builder = val
                        } 
                    }
                })
            }
        },
        initEmptyTableData() {
            this.formData.goods = []
            for (let index = 0; index < 8; index++) {
                this.formData.goods.push({
                    index: index+1,
                    name: '',
                    goods_no: '',
                    barcode: '',
                    num: '',
                    unit_price: '',
                    unitName: '',
                    specifications: '',
                    current_inventory_quantity: '',
                    remark: ''
                })
            }
        },
        // 获取单位等级
        getUnitLevels(cus_level) {
            getPriceLevel({corp: this.corp, is_start: 1}).then(res => {
                this.priceLevels = res.data.data.level_list.filter((item, index) => {
                    item.price_value = '0.00'
                    if (cus_level&&cus_level==item.id){
                        this.current_customer_price_level = item.price_column_name
                    }
                    return item
                })
                this.getPriceRememberSettings()
            })
        },
        // 获取价格记忆设置
        getPriceRememberSettings() {
            getPriceRemember({corp_id: this.corp}).then(res => {
                this.showPostStatus = res.data.sale_order_show_delivery_status || false
            })
        },
        searchProducts(query, type) {
            if (query !== '') {
                let params = {
                    corp: this.corp,
                    customer_id: this.formData.customer
                }
                if (type && type=='scan'){
                    params.goods_unit_deputy__barcode = query
                }else {
                    params.search = query
                }
                listProduct(params).then(res => {
                    if (type && type=='scan'){
                        let list = res.data.data.good_list
                        if (!list.length){
                            this.$alert('识别的商品（条形码：'+query+'）不存在', '提示', {
                                confirmButtonText: '确定',
                                type: 'warning'
                            })
                        }else{
                            // 统计id为空的个数
                            const emptyIdCount = this.formData.goods.filter(item => !item.id).length;
                            // 若所有id均不为空，则新增数据
                            if (emptyIdCount === 0){
                                this.addCell()
                            }
                            // 查找第一个id为空的index
                            const firstEmptyIndex = this.formData.goods.findIndex(item => !item.id);
                            this.formData.goods[firstEmptyIndex].id = list[0].id

                            this.searchGoods = list
                            this.cellChange(list[0].id, {index: firstEmptyIndex+1})
                        }
                        return
                    }
                    this.searchGoods = res.data.data.good_list.filter(item => {
                        item.cateName = item.category_detail.name
                        item.disabled = false
                        return item
                    })

                    this.searchGoods.unshift({
                        name: '商品名称',
                        goods_no: '商品编号',
                        barcode: '条形码',
                        current_inventory_quantity: '商品库存',
                        id: 'table_header',
                        disabled: true
                    })
                })
            }
        },
        cellChange(val, row) {
            let that = this
            this.searchGoods.forEach(item => {
                if (item.id === val){
                    that.formData.goods.forEach((_item, _index) => {
                        if (_item.id === val && row.index===_index+1){
                            if (item.is_start_batch || item.is_start_sell_by_date){
                                // _item.id = ''
                                item.index = _item.index
                                that.chooseNumberPopShow(item, '1')
                            }else{
                                _item.name = item.name
                                _item.barcode = item.barcode
                                _item.current_inventory_quantity = item.current_inventory_quantity
                                _item.goods_no = item.goods_no
                                _item.num = 1
                                _item.id = item.id
                                _item.specifications = item.specifications
                                _item.unitName = item.unit_show?item.unit_show.name:item.unit
                                _item.unit_price = item.unit_retail_price?parseFloat(item.unit_retail_price):'0'
                                _item.is_start_batch = item.is_start_batch || false,
                                _item.is_start_sell_by_date = item.is_start_sell_by_date || false
                                _item.is_multi_unit = item.is_multi_unit
                                _item.remark = item.remark
                                if (item.is_multi_unit){  //多单位
                                    _item.unitArray = item.unit_deputy_show.filter(_it => {
                                        _it.selected = false
                                        if (_it.is_main) {  //主单位，默认勾选
                                            _it.selected = true
                                            _item.select_unit_id = _it.goods_unit
                                            _it.formatterName = _it.unit_name
                                            that.handlePriceLevelValue(_it)
                                        }else{
                                            let formatterName = '1'+_it.unit_name+'='+parseFloat(_it.deputy_ratio)+_item.unitName
                                            _it.formatterName = formatterName
                                        }
                                        return _it
                                    })
                                }else{
                                    that.handlePriceLevelValue(item.unit_deputy_show[0])
                                }
                            }
                            that.searchGoods = []
                        }
                    })
                    that.$forceUpdate()
                    that.handleRepeatData()
                    that.recalculate()
                    that.$nextTick(() => {
                        that.handleStyle()
                    })
                }
            })
        },
        // 处理重复数据
        handleRepeatData() {
            let array = this.formData.goods
            
            // 步骤1：分离有效 id 和无效 id 的项
            const validItems = array.filter(item => (item.id && !item.is_multi_unit && !item.is_start_batch && !item.is_start_sell_by_date)); // 过滤出有效 id 的项
            const invalidItems = array.filter(item => (!item.id || item.is_multi_unit || item.is_start_batch || item.is_start_sell_by_date)); // 保留无效 id 的项

            // 步骤2：合并有效 id 的项（num 累加）
            const mergedMap = validItems.reduce((map, item) => {
                const { id, num } = item;
                if (map.has(id)) {
                    map.get(id).num += num; // 累加 num
                } else {
                    map.set(id, { ...item }); // 初始化新条目
                }
                return map;
            }, new Map());

            // 步骤3：合并结果 = 有效项合并结果 + 无效项
            const mergedArray = [...mergedMap.values(), ...invalidItems];
            console.log(mergedArray)
            if (mergedArray.length < 8){
                for (let index = 0; index < 8; index++) {
                    if (mergedArray.length > index){
                        mergedArray[index].index = index+1
                    }else{
                        mergedArray.push({
                            index: index+1,
                            name: '',
                            goods_no: '',
                            barcode: '',
                            num: '',
                            unit_price: '',
                            unitName: '',
                            specifications: '',
                            current_inventory_quantity: '',
                            batch_name: '',
                            produce_date: ''
                        })
                    }
                }
            }else{
                mergedArray.forEach((item, index) => {
                    item.index = index+1
                })
            }
            this.formData.goods = mergedArray
        },
        handlePriceLevelValue(item) {
            this.priceLevels.forEach(_item => {
                _item.price_value = item[_item.price_column_name] || '0.00'
            })
        },
        searchFocus(val, row) {
            let index = row.index-1
            document.getElementsByClassName('prod_search')[index].classList.remove('show_product_cell')
        },
        searchBlur(val, row) {
            if (!val.target.value){
                let index = row.index-1
                if (!this.formData.goods[index].id){
                    document.getElementsByClassName('prod_search')[index].classList.add('show_product_cell')
                }
            }
        },
        // 按条件筛选
        handleQuery() {
            this.pageParam.page = 1
            this.goodsList = []
            this.loadOver = false
            this.getProductLists()
        },
        // 批次、保质期选择数量弹窗
        chooseNumberPopShow(row, type) {
            this.chooseNumberInfo = row
            this.popShowType = type
            // 保质期查询
            getProductDate({
                corp: this.corp,
                goods_id: row.id,
                goods_name: row.name,
                num_ne: '0'
            }).then(res => {
                this.batchLists = res.data.data.batch_date_list.filter((item, index) => {
                    item.index = index+1
                    item.current_inventory_quantity = parseFloat(item.num)
                    item.is_start_batch = item.goods_details.is_start_batch
                    item.is_start_sell_by_date = item.goods_details.is_start_sell_by_date
                    item.batch_name = item.batch_name || '未设批次'
                    if (row.countInfo && row.countInfo.length){
                        row.countInfo.forEach(_item => {
                            if (item.id === _item.batch_date_account_id){
                                item.number = _item.num
                            }
                        })
                    }
                    return item
                })
                this.showChooseNumberPop = true
            })
        },
        hideChooseNumber() {
            let index = this.chooseNumberInfo.index
            if (index){
                this.formData.goods[index-1].id = ''
                document.getElementsByClassName('prod_search')[index-1].classList.add('show_product_cell')
            }
            this.showChooseNumberPop = false                
        },
        chooseNumberOk() {
            let count = 0
            let countInfo = []
            this.batchLists.forEach(item => {
                if (parseFloat(item.number) > 0){
                    countInfo.push({
                        num: item.number,
                        batch_date_account_id: item.id
                    })
                    count = this.$common.plusFloat(count, parseFloat(item.number))
                }
            })
            
            let that = this
            if (this.popShowType == '1'){
                let cell = {
                    name: this.chooseNumberInfo.name,
                    barcode: this.chooseNumberInfo.barcode,
                    current_inventory_quantity: this.chooseNumberInfo.current_inventory_quantity,
                    goods_no: this.chooseNumberInfo.goods_no,
                    num: count,
                    id: this.chooseNumberInfo.id,
                    specifications: this.chooseNumberInfo.specifications,
                    unitName: this.chooseNumberInfo.unit_show?this.chooseNumberInfo.unit_show.name:this.chooseNumberInfo.unit,
                    unit_price: this.chooseNumberInfo.unit_retail_price?parseFloat(this.chooseNumberInfo.unit_retail_price):'0',
                    is_start_batch: this.chooseNumberInfo.is_start_batch || false,
                    is_start_sell_by_date: this.chooseNumberInfo.is_start_sell_by_date || false,
                    is_multi_unit: this.chooseNumberInfo.is_multi_unit || false,
                    countInfo: countInfo,
                    unit_deputy_show: this.chooseNumberInfo.unit_deputy_show
                }
                this.formData.goods = this.formData.goods.map(item => 
                    item.index === that.chooseNumberInfo.index ? Object.assign({}, item, cell) : item
                );
                this.formData.goods.forEach(item => {
                    if (item.index === that.chooseNumberInfo.index) {
                        document.getElementsByClassName('prod_search')[item.index-1].classList.remove('show_product_cell')
                        if (that.chooseNumberInfo.is_multi_unit){  //多单位
                            item.unitArray = that.chooseNumberInfo.unit_deputy_show.filter(_it => {
                                _it.selected = false
                                if (_it.is_main) {  //主单位，默认勾选
                                    _it.selected = true
                                    item.select_unit_id = _it.goods_unit
                                    _it.formatterName = _it.unit_name
                                    that.handlePriceLevelValue(_it)
                                }else{
                                    if (!item.unitName) {
                                        let finditem = item.unit_deputy_show.find(el => el.is_main)
                                        item.unitName = finditem.unit_name
                                    }
                                    let formatterName = '1'+_it.unit_name+'='+parseFloat(_it.deputy_ratio)+item.unitName
                                    _it.formatterName = formatterName
                                }
                                return _it
                            })
                        }else{
                            that.handlePriceLevelValue(that.chooseNumberInfo.unit_deputy_show[0])
                        }
                    } 
                })
                that.recalculate()
            }else {
                this.goodsList.forEach(item => {
                    if (item.id === this.chooseNumberInfo.id){
                        item.select_num = count
                        item.countInfo = countInfo
                        this.$refs.goodsTable.toggleRowSelection(item, true)
                    }
                })
            }
            this.showChooseNumberPop = false
            this.$forceUpdate()
        },
        batchBlur(val, row) {
            let count = val.target.value
            count = count.replace(/[^0-9.]/g, ''); // 只允许数字和小数点
            const parts = count.split('.');
            if (parts.length > 2) {
                count = parts[0] + '.' + parts.slice(1).join(''); // 只取第一个小数点之前的部分
            }
            if (!count){
                count = 0
            }

            val.target.value = parseFloat(count)
            row.number = parseFloat(count)
        },
        unitChange(val, row, type) {
            console.log(val)
            if (type && type == 'goods'){
                const findItem = row.unitArray.find(_item => _item.goods_unit==row.select_unit_id)
                let all_num = parseFloat(row.num)
                let max = row.current_inventory_quantity
                if (findItem && findItem.deputy_ratio) {
                    all_num = this.$common.multiplyFloat(parseFloat(all_num), parseFloat(findItem.deputy_ratio))
                }
                if (all_num > max){
                    this.formData.goods = this.formData.goods.filter(_item => {
                        if (_item.id == row.id) {
                            if (_item.is_multi_unit){
                                _item.num = Math.trunc(max / parseFloat(findItem.deputy_ratio))
                            }else{
                                _item.num = max
                            }
                            _item.select_num = _item.num
                        }
                        return _item
                    })
                }
            }

            let price = 0
            row.unitArray.forEach(item => {
                item.selected = false
                if (item.goods_unit == val) {
                    price = item[this.current_customer_price_level]?
                        parseFloat(item[this.current_customer_price_level]):'0.00'
                    item.selected = true
                    row.goods_unit = item.goods_unit
                    this.handlePriceLevelValue(item)
                }
            })
            row.unit_price = price
            this.recalculate()
        },
        // 获取商品列表
        getProductLists() {
            let that = this
            this.queryParams.corp = this.corp
            this.queryParams.customer_id = that.formData.customer
            let params = Object.assign({}, this.queryParams, this.pageParam)
            listProduct(params).then(res => {
                let list = res.data.data.good_list.filter((item, index) => {
                    item.cateName = item.category_detail.name
                    if (item.image_show && item.image_show.url){
                        item.imageUrl = item.image_show.url
                    }else{
                        item.imageUrl = 'https://anhuiyaoying.com/icon/default.png'
                    }
                    item.select_num = 0,
                    item.goods_no = item.goods_no || ''
                    item.specifications = item.specifications || ''
                    item.unitName = item.unit_show?item.unit_show.name:item.unit
                    if (item.is_multi_unit){  //多单位
                        item.unitArray = item.unit_deputy_show.filter(_it => {
                            _it.selected = false
                            if (_it.is_main) {  //主单位，默认勾选
                                _it.selected = true
                                item.select_unit_id = _it.goods_unit
                                _it.formatterName = _it.unit_name
                                that.handlePriceLevelValue(_it)
                            }else{
                                if (!item.unitName) {
                                    let finditem = item.unit_deputy_show.find(el => el.is_main)
                                    item.unitName = finditem.unit_name
                                }
                                let formatterName = '1'+_it.unit_name+'='+parseFloat(_it.deputy_ratio)+item.unitName
                                _it.formatterName = formatterName
                            }
                            return _it
                        })
                    }
                    let mainUnitItem = item.unit_deputy_show.find(el => el.is_main)
                    item.priceLevels = this.priceLevels.map(_item => ({
                        ..._item, // 浅拷贝对象
                        price_value: mainUnitItem[_item.price_column_name] || '0.00' // 覆盖属性
                    }))
                    // item.testFlag = index+' ---- '+JSON.stringify(item.priceLevels[0])

                    if (that.current_customer_price_level){
                        item.unit_price = item.priceLevels.find(_item => _item.price_column_name==that.current_customer_price_level).price_value
                    }else{
                        item.unit_price = item.priceLevels.find(_item => _item.price_column_name=='unit_retail_price').price_value
                    }
                    item.current_inventory_quantity = parseFloat(item.current_inventory_quantity)
                    return item
                })

                that.goodsList = that.goodsList.concat(list)
                that.total = res.data.data.total
                // 合并已选数据
                // that.joinArray()
                // 勾选已选择行
                that.handleSelectRow()
                // 启用滚动加载
                that.loadOver = false;
            })
        },
        joinArray() {
            const map = new Map();
            this.goodsList.forEach(item => {
                map.set(item.id, { ...item });
            });

            this.formData.goods.forEach(item => {
                if (map.has(item.id)) {
                    const existingItem = map.get(item.id);
                    map.set(item.id, { ...existingItem, ...item });
                } else {
                    if (item.id) {
                        map.set(item.id, { ...item });
                    }
                }
            });
            this.goodsList = Array.from(map.values());
        },
        handleSelectRow() {
            let that = this
            this.$nextTick(() => {
                const table = that.$refs.goodsTable;
                if (table && table.toggleRowSelection) {
                    table.clearSelection();
                    if (that.middleGoods.length){
                        that.middleGoods.forEach(item => {
                            const rowToSelect = that.goodsList.find(order => order.id === item.id);
                            if (rowToSelect) {
                                table.toggleRowSelection(rowToSelect, true);
                            }
                        })
                    }
                }
            })
        },
        // 获取商品分类
        getProductCategory() {
            let that = this
            getTreeList({corp: this.corp}).then(res => {
                let categorys = res.data.data.category_list.filter(item => { return !item.parent })
                that.categorys = categorys
            })
        },
        // 分类点击
        itemChanged(val) {
            if (val && val.length>0){
                if (val.length === 1){
                    this.queryParams.category_one_level = val[0]
                    this.queryParams.category = null
                }else if (val.length === 2){
                    this.queryParams.category_one_level = null
                    this.queryParams.category = val[1]
                }
            }else{
                this.queryParams.category_one_level = null
                this.queryParams.category = null
            }
        },
        // 多选框选中数据
        handleSelectionChange (selection) {
            if (selection.length){
                this.chooseGoods = selection
            }
        },
        // 加载下一页数据
        loadNextPage() {
            // 禁用滚动加载
            this.loadOver = true;
            let allPage = 0
            if (this.total === 0) return

            if (this.total % this.pageParam.num === 0){  //整除
                allPage = Math.trunc(this.total / this.pageParam.num)
            }else{
                allPage = Math.trunc(this.total / this.pageParam.num) + 1
            }
            
            console.log(allPage, this.pageParam.page)
            this.pageParam.page ++
            // this.loadOver = false
            if (this.pageParam.page > allPage){
                this.loadOver = true
                return
            }
            this.middleGoods = this.chooseGoods
            this.getProductLists()
        },
        // 动态计算价格 
        recalculate() {
            // console.log(val.target.value)
            let totalPrice = 0, totalCount = 0, orderPrice = 0;
            this.formData.goods.forEach(item => {
                if (item.id){
                    totalPrice += (item.unit_price * parseFloat(item.num))
                    totalCount += parseFloat(item.num)
                }
            })
            this.formData.goods_sum_price = parseFloat(totalPrice.toFixed(2))
            this.formData.goods_count = totalCount
            orderPrice = parseFloat((this.formData.goods_sum_price - this.formData.payment_discount).toFixed(2))
            this.formData.order_price = orderPrice

            if (this.exchangeId) {  //重新计算尾款
                let order_price = parseFloat(this.formData.order_price)
                let prepaid_money = parseFloat(this.formData.prepaid_money)
                this.formData.pending_payment = this.$common.subtractFloat(order_price, prepaid_money)
            }
            this.$forceUpdate()
        },
        // 数量输入框监听实时输入，判断是否超库存
        judgeCount(val, item) {
            let count = val.target.value
            count = count.replace(/[^0-9.]/g, ''); // 只允许数字和小数点
            const parts = count.split('.');
            if (parts.length > 2) {
                count = parts[0] + '.' + parts.slice(1).join(''); // 只取第一个小数点之前的部分
            }
            console.log(count)

            let max = parseFloat(item.current_inventory_quantity)
            if (item.is_multi_unit){ //多单位
                const findItem = item.unitArray.find(_item => _item.goods_unit==item.select_unit_id)
                let all_num = 0
                if (findItem && findItem.deputy_ratio) {
                    all_num = this.$common.multiplyFloat(parseFloat(count), parseFloat(findItem.deputy_ratio))
                }
                if (all_num > max){
                    this.formData.goods = this.formData.goods.filter(_item => {
                        if (_item.id == item.id) {
                            _item.num = Math.trunc(max / parseFloat(findItem.deputy_ratio))
                            val.target.value = _item.num;
                        }
                        return _item
                    })
                }
            }else{
                if (parseFloat(count) > max){  //超库存
                    this.formData.goods = this.formData.goods.filter(_item => {
                        if (_item.id == item.id) {
                            _item.num = max
                        }
                        return _item
                    })
                    val.target.value = max;
                }else {
                    val.target.value = parseFloat(count)
                }
            }
        },
        countBlur(val, row) {
            let count = val.target.value
            count = count.replace(/[^0-9.]/g, ''); // 只允许数字和小数点
            const parts = count.split('.');
            if (parts.length > 2) {
                count = parts[0] + '.' + parts.slice(1).join(''); // 只取第一个小数点之前的部分
            }
            if (!count || parseFloat(count)===0){
                count = 1
            }

            val.target.value = parseFloat(count)
            row.num = parseFloat(count)
            this.recalculate()
        },
        priceBlur(val, row) {
            let count = val.target.value
            count = count.replace(/[^0-9.]/g, ''); // 只允许数字和小数点
            const parts = count.split('.');
            if (parts.length > 2) {
                count = parts[0] + '.' + parts.slice(1).join(''); // 只取第一个小数点之前的部分
            }
            if (!count){
                count = 0
            }

            val.target.value = parseFloat(count)
            row.unit_price = parseFloat(count)
            // row.visible = false
            this.recalculate()
        },
        handleCommand(command, row) {
            let item = this.priceLevels.find(_item => _item.id===command)
            row.unit_price = item.price_value
        },  
        handleCommand1(command, row) {
            let item = row.priceLevels.find(_item => _item.id===command)
            row.unit_price = item.price_value
        },  
        // 收款记录
        showRecord() {
            this.records = this.formData.payment_record.filter(item => {
                item.timestamp = item.update_datetime.substring(0, 16).replace('T', ' ')
                item.content = "已收：￥"+item.current_paid_payment
                return item
            })
            this.showRecordAlert = true
        },
        // 发票相关
        showAddInvoicePop() {
            this.invoiceDialogTitle = '新增开票'
            this.showAddInvoice = true
        },
        addInvoice() {
            var that = this
            that.$refs['invoiceForm'].validate(valid => {
                if(!valid) return

                if (that.invoiceDialogTitle == '新增开票'){
                    that.formData.invoice_list.push({
                        index: that.formData.invoice_list.length,
                        invoice_no: that.invoiceForm.invoice_no,
                        remark: that.invoiceForm.remark
                    })
                }else {
                    that.formData.invoice_list.forEach(item => {
                        if (item.index === that.invoiceForm.index){
                            item.invoice_no = that.invoiceForm.invoice_no
                            item.remark = that.invoiceForm.remark
                        }
                    })
                }
                that.invoiceForm.invoice_no = ''
                that.invoiceForm.remark = ''
                that.showAddInvoice = false
            })
        },
        updateInvoice(item) {
            this.invoiceForm.index = item.index
            this.invoiceForm.invoice_no = item.invoice_no
            this.invoiceForm.remark = item.remark
            this.invoiceDialogTitle = '编辑开票'
            this.showAddInvoice = true
        },
        removeInvoice(item) {
            let res = this.formData.invoice_list.filter(_item => _item.index != item.index)
            res.forEach((_item, index) => {
                _item.index = index
            })
            this.$set(this.formData, 'invoice_list', res)
            this.$forceUpdate()
        },
        // 选择地址
        cityChanged(val) {
            if (val && val.length===3){
                let path = this.hashTable.get(val[2]).path
                let names = path.split('&')
                
                this.formData.extend_data.province_code = val[0]
                this.formData.extend_data.city_code = val[1]
                this.formData.extend_data.area_code = val[2]
                this.formData.extend_data.province_name = names[0]
                this.formData.extend_data.city_name = names[1]
                this.formData.extend_data.area_name = names[2]
            }
        },
        // 收尾款
        showReceivedMoney() {
            this.paymentForm.corp = this.formData.corp
            this.paymentForm.customer = this.formData.customer
            this.paymentForm.handler_user = this.formData.handler_user
            this.paymentForm.pay_type = 2
            this.paymentForm.orders_date = moment().format('yyyy-MM-DD')
            this.paymentForm.orders_fee = this.formData.unPayMoney
            this.paymentForm.remark = ''
            this.showPaymentPop = true
        },
        // 创建收款单
        createReceiveOrder() {
            if (parseFloat(this.paymentForm.orders_fee) > parseFloat(this.formData.unPayMoney)){
                this.$message.error('本次收款金额大于待收款金额，请重新输入')
                return
            }
            this.paymentForm.order_relations = [{
                related_order_id: this.orderId,
                orders_fee: parseFloat(this.paymentForm.orders_fee)
            }]

            addReceivePayment(this.paymentForm).then(res => {
                if (res.code == 200){
                    let isShow = res.data.data.is_show
                    let msg = isShow?'收款成功':'收款成功，请等待审核员审核'
                    this.$message({
                        message: msg,
                        type: 'success'
                    })
                    this.getOrderInfo()
                    this.showPaymentPop = false
                }
            })
        },
        // 自定义按钮事件
        handleButtonClick(item) {
            switch (item.id) {
                case '1':   // 保存草稿
                    this.saveAsDraft()
                    break;
                case '2':   // 提交
                    this.beforeSubmit()
                    break;
                case '3':   // 取消
                    this.goBack()
                    break;
            
                default:
                    break;
            }
        },
        // 保存草稿
        saveAsDraft() {
            this.formData.is_draft = true
            this.formData.draft_payment = parseFloat(this.formData.current_paid_payment)
            this.submit()
        },
        // 提交
        beforeSubmit() {
            var that = this
            that.$refs['formData'].validate(valid => {
                if(!valid) return

                if (!that.formData.goods.length){
                    that.$message.error('请至少添加一个商品') 
                    return
                }
                that.submit()
            })
        },
        submit(type) {
            this.formData.sale = this.formData.sale.filter(item => {
                delete item['index']
                delete item['name']
                delete item['type']
                item.commission = parseFloat(item.commission)
                return item
            })
            this.formData.builder = this.formData.builder.filter(item => {
                delete item['index']
                delete item['name']
                delete item['type']
                item.commission = parseFloat(item.commission)
                return item
            })
            let allProds = []
            this.formData.goods.forEach(item => {
                if (item.id){
                    if (item.countInfo && item.countInfo.length) {  //多批次
                        item.countInfo.forEach(_item => {
                            const newItem = { ...item }; // 浅拷贝（若嵌套层数深需用深拷贝）
                            newItem.num = _item.num;
                            newItem.batch_date_account_id = _item.batch_date_account_id;
                            allProds.push(newItem);
                        })
                    }else{
                        allProds.push(item)
                    }
                }
            })
            this.formData.goods = allProds
            
            this.formData.goods = this.formData.goods.filter(item => {
                delete item['goods_name']
                delete item['index']
                delete item['countInfo']
                if (!item.goods_id){
                    item.goods_id = item.id
                }
                
                item.num = parseFloat(item.num)
                item.unit_price = parseFloat(item.unit_price)
                if (item.is_multi_unit){  //多单位
                    item.unitArray.forEach((ele, index) => {
                        if (ele.selected && !ele.is_main){
                            item.deputy_price = item.unit_price
                            item.deputy_num = item.num
                            item.deputy_ratio = parseFloat(ele.deputy_ratio)
                            item.deputy_unit_id = ele.id
                            item.num = this.$common.multiplyFloat(item.deputy_num, item.deputy_ratio).toFixed(2)
                            item.unit_price = this.$common.multiplyDivision(item.deputy_price, item.deputy_ratio).toFixed(2)
                        }
                    })
                }
                return item
            })
            this.formData.order_price = this.formData.order_price?parseFloat(this.formData.order_price):0
            this.formData.payment_discount = this.formData.payment_discount?parseFloat(this.formData.payment_discount):0
            this.formData.rebates = this.formData.rebates?parseFloat(this.formData.rebates):0
            this.formData.current_paid_payment = this.formData.current_paid_payment?parseFloat(this.formData.current_paid_payment):0
            this.formData.goods_sum_price = this.formData.goods_sum_price?parseFloat(this.formData.goods_sum_price):0
            this.formData.goods_count = this.formData.goods_count?parseFloat(this.formData.goods_count):0

            if (!this.formData.is_need_invoice){
                this.formData.invoice_list = null
            }else {
                this.formData.invoice_list.forEach(item => {
                    delete item['index']
                })
            }

            if (type){
                delete this.formData['id']
            }
            if (this.formData.is_draft){  //草稿
                this.formData.current_paid_payment = 0
            }
            this.formData.corp = this.corp
            if (this.orderId && !type && !this.exchangeId){  //编辑
                this.formData.pending_payment = this.formData.pending_payment?parseFloat(this.formData.pending_payment):0
                this.formData.paid_payment = this.formData.paid_payment?parseFloat(this.formData.paid_payment):0
                updateOrder(this.orderId, this.formData).then(res => {
                    if (res.msg.indexOf('库存') > -1) {
                        this.$message.error(res.msg)
                        return
                    }

                    if (!this.formData.is_draft){
                        let isShow = res.data.data.is_show
                        if (!isShow){
                            this.doPushMessages()
                        }
                        this.$message({
                            message: isShow?'修改成功':'修改成功，请等待审核员审核',
                            type: 'success'
                        })
                    }
                    this.$emit('success')
                })
            }else{
                if (this.exchangeId){
                    this.formData.reserve_order_id = parseInt(this.exchangeId)
                    this.formData.pending_payment = parseFloat(this.formData.pending_payment)
                }
                addOrder(this.formData).then(res => {
                    if (res.msg.indexOf('库存') > -1) {
                        this.$message.error(res.msg)
                        return
                    }

                    if (!this.formData.is_draft){
                        let isShow = res.data.data.is_show
                        if (!isShow){
                            this.doPushMessages()
                        }
                        this.$message({
                            message: isShow?'新增成功':'新增成功，请等待审核员审核',
                            type: 'success'
                        })
                    }
                    this.$emit('success')
                })
            }
        },
        // 发送推送消息
        doPushMessages() {

        },
    }
}
</script>

<style lang="less" scoped>
    @import '../../../style/mixin.less';
    .send_btn {
        position: absolute;
        right: 0;
        top: 0;
    }
    .send_view {
        padding: 15px;
        border-radius: 4px;
        margin: 4px 0 20px 30px;
        border: 1px solid #d7d7d7;
        background-color: #f2f2f2;
        font-size: 13px;
        .title {
            display: flex;
            align-items: center;
            gap: 20px;
        }
        .contents {
            margin-top: 20px;
            .address {
                font-size: 14px;
                color: #333;
                .base {
                    display: flex;
                    align-items: center;
                    width: 100%;
                    gap: 50px;
                    .info {
                        display: inline-flex;
                        align-items: center;
                        gap: 15px;
                    }
                }
                .addr {
                    display: flex;
                    align-items: center;
                    width: 100%;
                    justify-content: space-between;
                    margin-top: 20px;
                    .left {
                        display: flex;
                        align-items: center;
                        flex-direction: column;
                        gap: 10px;
                    }
                    .btns {
                        display: flex;
                        align-items: center;
                        gap: 15px;
                        font-size: 14px;
                        .set_default {
                            cursor: pointer;
                        }
                        .remove {
                            color: red;
                            cursor: pointer;
                        }
                    }
                }
            }
            .fastmail {
                .item {
                    display: flex;
                    align-items: center;
                    gap: 20px;
                    font-size: 14px;
                }
            }
        }
    }
    .invoice_view {
        display: flex;
        flex-direction: column;
        padding: 15px;
        border-radius: 4px;
        margin: 4px 0 20px 30px;
        border: 1px solid #d7d7d7;
        background-color: #f2f2f2;
        font-size: 13px;
        .cell {
            display: flex;
            padding-bottom: 5px;
            .info {
                width: 100%;
                word-break: break-all;
                line-height: 1.5;
                color: #000000a6;
                .update {
                    color: @blue;
                    padding: 0 10px;
                    cursor: pointer;
                }
                .remove {
                    color: red;
                    padding: 0 2px;
                }
            }
        }
        .add_btn {
            width: 86px;
            height: 32px;
            text-align: center;
            line-height: 32px;
            background: #FFF;
            border: 1px solid #ccc;
            border-radius: 5px;
            margin-top: 10px;
            cursor: pointer;
        }
    }
    .batch_view {
        .header {
            display: flex;
            align-items: center;
            gap: 100px;
            font-size: 14px;
        }
    }
    .form_title {
        font-size: 14px;
        font-weight: bold;
        color: #333;
        padding: 15px 0;
    }
    .set_user_none {
        margin-left: 10px;
        font-size: 14px;
        color: @blue;
        &:hover {
            cursor: pointer;
        }
    }
    .set_user_done {
        margin-left: 10px;
        font-size: 14px;
        &:hover {
            color: @blue;
            cursor: pointer;
        }
    }
    .set_user_dialog {
        padding: 0 10px;
        max-height: 300px;
        overflow-y: auto;
        .item {
            display: flex;
            align-items: center;
            padding-bottom: 10px;
            justify-content: space-between;
            width: 90%;
            .btns {
                display: inline-flex;
                align-items: center;
                font-size: 20px;
                margin-left: 10px;
                width: 60px;
                .add {
                    color: @blue;
                    margin-right: 20px;
                    &:hover{
                        cursor: pointer;
                    }
                }
                .remove {
                    color: red;
                    &:hover{
                        cursor: pointer;
                    }
                }
            }
        }
    }
    .goods_add {
        display: flex;
        align-items: center;
        justify-content: end;
        padding-right: 20px;
        cursor: pointer;
        color: @blue;
        i {
            font-size: 16px;
        }
        span {
            margin-left: 8px;
            font-weight: bold;
            font-size: 14px;
        }
    }
    .goods_list {
        padding: 0 10px;
        max-height: 460px;
        overflow-y: auto;
    }
    .inner_input {
        width: 80px;
        height: 36px;
        line-height: 36px;
        font-size: 14px;
        border: 1px solid #DCDFE6;
        border-radius: 4px;
        background-color: #FFF;
        box-sizing: border-box;
        color: #606266;
        padding: 0 12px;
    }
    .file_list {
        font-size: 13px;
        padding-left: 40px;
        .file {
            cursor: pointer;
            padding-bottom: 10px;
            &:hover {
                color: @blue;
            }
        }
    }
    .record {
        color: @blue;
        cursor: pointer;
        font-size: 14px;
        padding-right: 20px;
        font-weight: 500;
        text-align: right;;
    }
    .prod_table {
        margin-top: 15px;
        .original-dom {
            transition: opacity 0.3s ease;
            display: block;
            // &:hover {
            //     display: none;
            // }
        }
        .target-dom {
            transition: opacity 0.3s ease;
            display: none;
            align-items: center;
            gap: 10px;
            height: 100%;
            justify-content: center;
            cursor: pointer;
        }
        .prod_search {
            transition: opacity 0.3s ease;
            align-items: center;
            gap: 10px;
            min-height: 40px;
            justify-content: space-between;
            display: flex;
        }
        .show_product_cell {
            display: none;
        }
    }
    .price_levels {
        display: flex;
        flex-direction: column;
        .item {
            border-bottom: 1px solid #ccc;
            text-align: center;
            height: 44px;
            line-height: 44px;
            font-size: 14px;
            cursor: pointer;
            &:hover {
                background: @blue;
                color: #FFF;
            }
        }
    }
    .hide_input {
        opacity: 0;
        position: fixed;
        right: 0;
        top: 0;
    }
    .bottom {
        position: fixed;
        bottom: 0;
        left: 150px;
        right: 0;
        height: 50px;
        background: #fff;
        border: 1px solid #eee; /* 边框 */
        box-shadow: 0 -3px 6px rgba(0, 0, 0, 0.5); /* 上边框阴影 */
        display: flex;
        align-items: center;
        justify-content: end;
        .btns {
            padding: 0 30px;
            display: flex;
            align-items: center;
            gap: 12px;
            .btn {
                height: 32px;
                display: inline-flex;
                align-items: center;
            }
        }
    }
</style>

<style>
.el-collapse-item__header {
    font-size: 14px;
    font-weight: bold;
}
.el-collapse-item__arrow {
    font-size: 18px;
}
.el-select-dropdown__item.is-disabled {
    color: #333 !important;
    font-weight: bold !important;
}
.el-table--enable-row-hover .el-table__body tr:hover > td .cell .original-dom {
    display: none;
}
.el-table--enable-row-hover .el-table__body tr:hover > td .cell .target-dom {
    display: flex;
}
.el-table--enable-row-hover .el-table__body tr:hover > td .cell .show_product_cell {
    display: flex;
}
.my_popover .el-popover {
    top: 44px !important;
    padding: 0 !important;
    z-index: 99999;
}
.el-tooltip__popper {
    max-width: 800px;
    border: 1px solid #ccc !important;
}
.el-tooltip__popper.is-dark {
    background: #fff !important;
    color: #000 !important;
}
</style>
